package com.wkq.insertionsort;

import com.wkq.Sort;
import com.wkq.util.ArrayGenerator;
import com.wkq.util.SortingHelper;

/**
 * 换种方式实现插入排序法
 */
public enum InsertionSort2 implements Sort {
    INSTANCE;

    @Override
    public <E extends Comparable<E>> void sort(E[] arr) {
        //循环不变量：arr[0,i)未排序，[i,n)已排序，每次都将i插入到已排序数组中的合适位置
        for (int i = arr.length - 1; i >= 0; i--) {
            E temp = arr[i];
            int j;
            for (j = i; j + 1 < arr.length &&temp.compareTo(arr[j+1])>0; j++) {
                arr[j] = arr[j + 1];
            }
            arr[j] = temp;
        }
    }

    public static void main(String[] args) {
        int[] dataSize = {10000, 100000};
        for (int n : dataSize) {
            Integer[] arr = ArrayGenerator.generatorRandomArray(n, n);
            SortingHelper.sortTest(InsertionSort2.INSTANCE, arr);
        }
    }
}
